<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>用户注册</title>
    <!-- 可以引入外部CSS文件美化样式 -->
    <link href="/css/register.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        .password-container {
            position: relative;
        }

        .toggle-password {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
        }

        .modal {
            display: none; 
            position: fixed; 
            z-index: 1; 
            left: 0;
            top: 0;
            width: 100%; 
            height: 100%; 
            overflow: auto; 
            background-color: rgb(0,0,0); 
            background-color: rgba(0,0,0,0.4); 
        }

        .modal-content {
            background-color: #fefefe;
            margin: 15% auto; 
            padding: 20px;
            border: 1px solid #888;
            width: 80%; 
            max-width: 300px;
            text-align: center;
        }
    </style>
</head>
<body>
<div class="container">
    <h2>用户注册</h2>
    <form id="registerForm" action="http://localhost:8080/register" method="POST" onsubmit="return validateForm()">
        <!-- 用户名 -->
        <label for="username">用户名:</label><br>
        <input id="username" name="username" required type="text" onblur="checkUsername()"><br>
        <span id="username-error" style="color: red;"></span><br>

        <!-- 密码 -->
        <label for="password">密码:</label><br>
        <div class="password-container">
            <input id="password" name="password" required type="password" onblur="checkPasswordMatch()">
            <i class="fas fa-eye toggle-password" onclick="togglePasswordVisibility('password')"></i>
        </div><br>

        <!-- 确认密码 -->
        <label for="confirm-password">确认密码:</label><br>
        <div class="password-container">
            <input id="confirm-password" name="confirm-password" required type="password" onblur="checkPasswordMatch()">
            <i class="fas fa-eye toggle-password" onclick="togglePasswordVisibility('confirm-password')"></i>
        </div><br>
        <span id="password-error" style="color: red;"></span><br>

        <!-- 提交按钮 -->
        <input type="submit" value="注册">
    </form>
    <p>已有账号？<a href="http://localhost:8080/login">登录</a></p>
</div>

<!-- 成功提示弹窗 -->
<div id="successModal" class="modal">
    <div class="modal-content">
        <p>注册成功，<span id="countdown">3</span>s后将返回登录...</p>
    </div>
</div>
<script>
    function validateForm() {
        var password = document.getElementById("password").value;
        var confirmPassword = document.getElementById("confirm-password").value;
        var usernameError = document.getElementById("username-error").innerText;
        var passwordError = document.getElementById("password-error");

        passwordError.innerText = ""; // 清除之前的错误信息

        if (password !== confirmPassword) {
            passwordError.innerText = "密码和确认密码不一致，请重新输入。";
            return false; // 阻止表单提交
        }
        if (usernameError) {
            return false; // 阻止表单提交
        }
        return true; // 允许表单提交
    }

    function checkUsername() {
        var username = document.getElementById("username").value;
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "http://localhost:8080/check-username", true);
        xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                var response = JSON.parse(xhr.responseText);
                var usernameError = document.getElementById("username-error");
                if (response.exists) {
                    usernameError.innerText = "用户名已存在";
                } else {
                    usernameError.innerText = "";
                }
            }
        };
        xhr.send(JSON.stringify({username: username}));
    }

    function checkPasswordMatch() {
        var password = document.getElementById("password").value;
        var confirmPassword = document.getElementById("confirm-password").value;
        var passwordError = document.getElementById("password-error");

        if (confirmPassword === "") {
            passwordError.innerText = ""; // 如果确认密码为空，不显示错误信息
            return;
        }

        if (password !== confirmPassword) {
            passwordError.innerText = "密码和确认密码不一致，请重新输入。";
        } else {
            passwordError.innerText = "";
        }
    }

    function togglePasswordVisibility(id) {
        var passwordField = document.getElementById(id);
        var passwordFieldType = passwordField.type === 'password' ? 'text' : 'password';
        passwordField.type = passwordFieldType;
        var toggleIcon = passwordField.nextElementSibling;
        toggleIcon.classList.toggle('fa-eye');
        toggleIcon.classList.toggle('fa-eye-slash');
    }

    function showSuccessModal() {
        var modal = document.getElementById("successModal");
        modal.style.display = "block";
        
        var countdownElement = document.getElementById("countdown");
        var countdown = 3;
        countdownElement.innerText = countdown;

        var interval = setInterval(function() {
            countdown--;
            countdownElement.innerText = countdown;

            if (countdown <= 0) {
                clearInterval(interval);
                modal.style.display = "none";
                window.location.href = "/login";
            }
        }, 1000);
    }

    document.getElementById("registerForm").addEventListener("submit", function(event) {
        event.preventDefault(); // Prevent the default form submission

        if (validateForm()) {
            var xhr = new XMLHttpRequest();
            var form = event.target;
            var formData = new FormData(form);

            xhr.open("POST", form.action, true);
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    showSuccessModal();
                } else if (xhr.readyState === 4) {
                    // Handle error case
                    alert("注册失败，请重试。");
                }
            };

            xhr.send(formData);
        }
    });
</script>
</body>
</html>
